package com.gnerv.pabu.basic.core.service.impl;

import com.gnerv.pabu.basic.core.dto.SessionDTO;
import com.gnerv.pabu.basic.core.dto.UserLoginDTO;
import com.gnerv.pabu.basic.core.service.ISessionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 基础平台-回话 service 实现类
 *
 * @author zhang
 * @date 2019/12/4
 **/
@Slf4j
@Service
public class SessionServiceImpl implements ISessionService {

    @Autowired
    private MemorySessionDAO memorySessionDAO;

    @Autowired
    private DefaultWebSessionManager sessionManager;

    @Override
    public List<SessionDTO> listSession() {
        Collection<Session> activeSessions = sessionManager.getSessionDAO().getActiveSessions();
        List<SessionDTO> sessions = new ArrayList<>(activeSessions.size());

        for (Session activeSession : activeSessions) {
            SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) activeSession.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (!StringUtils.isEmpty(principalCollection)) {
                Serializable id = activeSession.getId();
                String host = activeSession.getHost();
                Date startTimestamp = activeSession.getStartTimestamp();
                Date lastAccessTime = activeSession.getLastAccessTime();

                UserLoginDTO userLoginDTO = (UserLoginDTO) principalCollection.getPrimaryPrincipal();
                SessionDTO sessionDTO = new SessionDTO();
                sessionDTO.setSessionId(String.valueOf(id));
                sessionDTO.setHost(host);
                sessionDTO.setStartTime(startTimestamp);
                sessionDTO.setLastAccessTime(lastAccessTime);

                sessionDTO.setUser(userLoginDTO);
                sessions.add(sessionDTO);
            }
        }
        return sessions;
    }

    @Override
    public boolean logout(String sessionId) {
        Session session = memorySessionDAO.readSession(sessionId);
        memorySessionDAO.delete(session);
        return true;
    }
}